import { createStore } from 'vuex'
import axios from 'axios';

export default createStore({
  state: {
    todos: [],
    total: 0,
    user: null,
    token: localStorage.getItem('token') || null
  },
  mutations: {
    setTodos(state, payload) {
      state.todos = payload.items;
      state.total = payload.total;
    },
    addTodo(state, todo) {
      state.todos.push(todo);
      state.total += 1;
    },
    removeTodo(state, id) {
      state.todos = state.todos.filter(todo => todo.id !== id);
      state.total -= 1;
    },
    SET_USER(state, user) {
      state.user = user;
    },
    SET_TOKEN(state, token) {
      state.token = token;
      localStorage.setItem('token', token);
      axios.defaults.headers.common['Authorization'] = `Bearer ${token}`;
    },
    CLEAR_AUTH(state) {
      state.user = null;
      state.token = null;
      localStorage.removeItem('token');
      delete axios.defaults.headers.common['Authorization'];
    }
  },
  actions: {
    async login({ commit }, credentials) {
      try {
        console.log('Sending login request with:', credentials);
        const response = await axios.post('/api/login', credentials);
        const { token, user } = response.data;
        
        console.log('Login response:', response.data);
        
        if (!user || !user.id) {
          throw new Error('Invalid user data received');
        }
        
        commit('SET_TOKEN', token);
        commit('SET_USER', user);
        return response.data;
      } catch (error) {
        console.error('Login error:', error);
        throw new Error(error.response?.data || '登录失败');
      }
    },
    async register(_, credentials) {
      try {
        const response = await axios.post('/api/register', credentials);
        return response.data;
      } catch (error) {
        throw new Error(error.response?.data || '注册失败');
      }
    },
    logout({ commit }) {
      commit('CLEAR_AUTH');
    },
    async fetchTodos({ commit }, { page, pageSize }) {
      try {
        const response = await axios.get(`/api/tasks?page=${page}&pageSize=${pageSize}`);
        commit('setTodos', response.data);
      } catch (error) {
        if (error.response?.status === 401) {
          commit('CLEAR_AUTH');
        }
        throw error;
      }
    },
    async createTodo({ commit, dispatch, state }, todo) {
      try {
        console.log('Creating todo:', todo);
        const response = await axios.post('/api/tasks', {
          ...todo,
          completed: false,
          user_id: state.user?.id
        });
        
        console.log('Todo created successfully:', response.data);
        commit('addTodo', response.data);
        await dispatch('fetchTodos', { page: 1, pageSize: 10 });
        return response.data;
      } catch (error) {
        console.error('Error creating todo:', error);
        if (error.response?.status === 401) {
          commit('CLEAR_AUTH');
        }
        const errorMessage = error.response?.status === 409 
          ? '该标题的任务已存在' 
          : '添加失败，请稍后重试';
        throw new Error(errorMessage);
      }
    },
    async deleteTodo({ commit, dispatch, state }, id) {
      try {
        await axios.delete('/api/tasks', { data: { id } });
        commit('removeTodo', id);
        
        const totalPages = Math.ceil((state.total - 1) / 10);
        const currentPage = Math.max(1, totalPages);
        
        await dispatch('fetchTodos', { 
          page: currentPage, 
          pageSize: 10 
        });
      } catch (error) {
        if (error.response?.status === 401) {
          commit('CLEAR_AUTH');
        }
        throw error;
      }
    },
    async searchTodos({ commit }, { query }) {
      try {
        const response = await axios.get(`/api/tasks?search=${query}`);
        commit('setTodos', response.data);
      } catch (error) {
        if (error.response?.status === 401) {
          commit('CLEAR_AUTH');
        }
        throw error;
      }
    },
    async updateTodoStatus({ commit, dispatch }, { id, completed }) {
      try {
        await axios.post('/api/tasks?action=update_status', {
          id,
          completed
        });
        await dispatch('fetchTodos', { page: 1, pageSize: 10 });
      } catch (error) {
        if (error.response?.status === 401) {
          commit('CLEAR_AUTH');
        }
        throw error;
      }
    },
  },
  modules: {
  },
});

if (localStorage.getItem('token')) {
  axios.defaults.headers.common['Authorization'] = `Bearer ${localStorage.getItem('token')}`;
}